#include <Windows.h>
#include <tchar.h>
#include <WindowsX.h>
#include "resource.h"

static HANDLE hMutex;

DWORD CALLBACK MutexProc(LPVOID lpData)
{
	HWND hListBox = (HWND)lpData;
	int nCount = 0;
	if (WaitForSingleObject(hMutex, INFINITE) == WAIT_OBJECT_0)
	{
		while (nCount < 50)
		{
			TCHAR szTmp[MAX_PATH];
			_stprintf(szTmp, _T("%02d => Thread(%0X)\n"), nCount + 1, GetCurrentThreadId());
			ListBox_AddString(hListBox, szTmp);
			nCount++;
		}
		ReleaseMutex(hMutex);
	}

	return 0;
}

DWORD CALLBACK ThreadProc(LPVOID lpData)
{
	hMutex = CreateMutex(NULL, FALSE, NULL);
	HANDLE hThreads[3];
	for (int ii = 0; ii < 3; ii++)
	{
		hThreads[ii] = CreateThread(NULL, 0, MutexProc, lpData, 0, NULL);
	}
	WaitForMultipleObjects(3, hThreads, TRUE, INFINITE);

	for (int ii = 0; ii < 3; ii++)
	{
		CloseHandle(hThreads[ii]);
		hThreads[ii] = NULL;
	}

	return 0;
}

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	static HWND hListBox;
	switch (nMsg)
	{
		case WM_INITDIALOG:
		{
			SetWindowText(hDlg, _T("Demo0090"));

			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtClient;
			GetClientRect(hDlg, &rtClient);
			SetWindowPos(hDlg, NULL, (nWidth - (rtClient.right - rtClient.left)) / 2, (nHeight - (rtClient.bottom - rtClient.top)) / 2, 0, 0, SWP_NOSIZE);
			
			hListBox = GetDlgItem(hDlg, IDC_LIST1);
			break;
		}
		case WM_COMMAND:
		{
			switch (LOWORD(wParam))
			{
				case IDC_BTNSTART:
				{
					CreateThread(NULL, 0, ThreadProc, (LPVOID)hListBox, 0, NULL);
					break;
				}
			}
			break;
		}
		case WM_CLOSE:
		{
			PostQuitMessage(0);
			break;
		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	HANDLE hMutex = CreateMutex(NULL, TRUE, _T("52C2AEAE-C7E8-4dfc-BE98-09970378B196_Demo0090"));
	if (INVALID_HANDLE_VALUE != hMutex && ERROR_ALREADY_EXISTS == GetLastError())
	{
		MessageBox(NULL, _T("The Application is existing!"), _T("Demo0090"), MB_OK);
		ReleaseMutex(hMutex);
		CloseHandle(hMutex);
		return FALSE;
	}

	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);

	return TRUE;
}